package repositories

import (
	"log"

	"gitee.com/yanxingshuyuan/backend/server/models"
	"github.com/jmoiron/sqlx"
)

type StatsRepo struct {
	db *sqlx.DB
}

func NewStatsRepo(db *sqlx.DB) *StatsRepo {
	return &StatsRepo{db: db}
}

func (r *StatsRepo) IncStar(mid string, pid string) int {
	sql :=
		`WITH input_rows(mid, pid, stars) 
		AS (VALUES ($1::char(8), $2::char(8), $3::integer))
		, ins AS (
			INSERT INTO stats (mid, pid, stars) 
			SELECT * FROM input_rows ON CONFLICT ON CONSTRAINT stats_pk DO UPDATE SET stars = stats.stars + 1
			RETURNING stars              
		)
		SELECT stars FROM ins UNION ALL SELECT s.stars as stars FROM input_rows JOIN stats s USING (mid, pid, stars)`
	stars := 0
	err := r.db.Get(&stars, sql, mid, pid, 1)
	if err != nil {
		log.Printf("Error increasing star count for %v:%v, error: %v\n", mid, pid, err)
		return stars
	}
	return stars
}

func (r *StatsRepo) ListStatsForMats(mids []string, pid string) (stats []models.Stats) {
	stats = make([]models.Stats, 0)
	if len(mids) == 0 {
		return
	}
	q, args, err := sqlx.In("SELECT * from stats where mid in (?) and pid = ?", mids, pid)
	if err != nil {
		log.Printf("Error making in query :%v, with error:%v\n", mids, err)
	}
	q = r.db.Rebind(q)
	err = r.db.Select(&stats, q, args...)
	if err != nil {
		log.Printf("Error getting stats: %v, with error: %v\n", mids, err)
	}
	return
}
